Introduction
A 1-dimensional array is a collection of elements stored in a contiguous memory block, where all elements are of the same data type. It allows you to store and access a sequence of values using a single index.
Declaration and Initialization
Declaration:
data_type array_name[size];
- data_type: Type of elements in the array (e.g., int, float, char).
- array_name: Name of the array.
- size: Number of elements the array can hold (must be a constant value or defined size).
Examples:
int numbers[5]; // Array to store 5 integers
int numbers[5] = {1, 2, 3, 4, 5}; // Initializes the array with specific values
int numbers[] = {1, 2, 3, 4, 5}; // Size automatically set to 5
Accessing and Iterating Elements
Accessing array elements:
numbers[0] = 10; // Assigns 10 to the first element
int x = numbers[2]; // Retrieves the third element
Iterating through a 1-D array:
#include < stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
printf("numbers[%d] = %d\n", i, numbers[i]);
}
return 0;
}
Output:
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50
Characteristics
- Fixed Size: Once declared, the size of an array cannot be changed.
- Contiguous Memory: Elements are stored in consecutive memory locations.
- Efficient Access: Index-based access allows for fast retrieval and modification.
- Default Values: Globally declared arrays are initialized to 0. Locally declared arrays have undefined values unless explicitly initialized.
Common Use Cases
- Storing a list of values (e.g., marks, temperatures, etc.).
- Simple data structures like queues and stacks.
- Iterative computation over a collection of items.